import { Injectable } from '@nestjs/common';
import { CreateDepartmentDto } from './dto/create-department.dto';
import { UpdateDepartmentDto } from './dto/update-department.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Department } from './entities/department.entity';
import { Like, Repository } from 'typeorm';
import { StatusText } from 'src/types/enum';
import { SearchDepartMentDto } from './dto/search-department.dto';

@Injectable()
export class DepartmentService {
  constructor(@InjectRepository(Department) private departmentRepository: Repository<Department>) { }

  async create(createStudentDto: CreateDepartmentDto) {
    const result = await this.departmentRepository.save(createStudentDto);
    return {
      code: 200,
      msg: StatusText.CREATE_SUCCESS,
      data: result
    };
  }

  async findAll(searchDepartMentDto: SearchDepartMentDto) {
    const search = {
      skip: (searchDepartMentDto.currentPage - 1) * searchDepartMentDto.pageSize,
      take: searchDepartMentDto.pageSize,
      where: {},
    }
    if (searchDepartMentDto.departmentName) {
      search.where = {
        departmentName: Like(`%${searchDepartMentDto.departmentName}%`)
      }
    }
    const result = await this.departmentRepository.find(search)
    return {
      code: 200,
      msg: StatusText.SEARCH_SUCCESS,
      data: {
        list: this.buildTree(result, 0)
      }
    };
  }

  private buildTree(departments: Department[], parentId: number | null): Department[] {
    return departments
      .filter(department => department.parentId === parentId)
      .map(department => ({
        ...department,
        children: this.buildTree(departments, department.departmentId),
      }));
  }

  async findOne(id: number) {
    const result = await this.departmentRepository.findOne({
      where: {
        departmentId: id
      }
    })
    return {
      code: 200,
      msg: StatusText.DETAIL_SUCCESS,
      data: result
    };
  }

  async update(id: number, updateStudentDto: UpdateDepartmentDto) {
    const result = await this.departmentRepository.update(id, updateStudentDto);
    return {
      code: 200,
      msg: StatusText.UPDATE_SUCCESS,
      data: result
    };
  }

  async remove(id: number) {
    const result = await this.departmentRepository.delete({
      departmentId: id
    })
    return {
      code: 200,
      msg: StatusText.DELETE_SUCCESS,
      data: result
    };
  }
}
